<?php

use app\modules\Admin\models\dianpuwithdrawModel as withdrawModel;
use app\modules\Admin\models\dianpuwithdrawlogModel as withdrawLogModel;
use Illuminate\Database\Capsule\Manager as DB;

#[店铺提现管理]
class DianpuwithdrawController extends AcommonController {

    public function init() {
        $this->model = new withdrawModel();
        $this->table = 'dianpu_withdraw';
        $this->primaryKey = 'id';
        parent::init();
    }
    
    #[店铺提现列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = $this->model->with(['dianpu', 'dianpumanager', 'member']);
            $mode = $this->get('mode', 'all');
            $post_data = $this->postData;
            switch ($mode){
                case 'canceled':
                    array_push($this->search,['status', '=', -2]);
                    break;
                case 'denied':
                    array_push($this->search,['status', '=', -1]);
                    break;
                case 'waiting':
                    array_push($this->search,['status', '=', 0]);
                    break;
                case 'agreed':
                    array_push($this->search,['status', '=', 1]);
                    break;
                case 'paid':
                    array_push($this->search,['status', '=', 2]);
                    break;
                case 'finished':
                    array_push($this->search,['status', '=', 3]);
                    break;
            }
            $type = $this->get('apply_type', 'all');
            if($type !== 'all' && in_array($type, ['bank', 'weixin', 'alipay'])){
                array_push($this->search, ['withdraw_type', '=', $type]);
            }
            if(isset($post_data['start_on']) && !empty($post_data['start_on'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['start_on']);
            }
            if(isset($post_data['end_on']) && !empty($post_data['end_on'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['end_on']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
                'dianpu_id' => 'dianpu_id',
                'dianpu_phone' => 'dianpu_phone',
                'company_name' => 'company_name',
                'dianpu_manager_id' => 'dianpu_manager_id',
                'dianpu_manager_phone' => 'dianpu_manager_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                //按申请人查找
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
                //按店铺查找
                if($post_data['keywordsType'] == $keywordsTypeArray['dianpu_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['dianpu_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['dianpu_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['dianpu_id', \app\modules\Admin\models\dianpuModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['company_name']){
                    array_push($this->condition_in, ['dianpu_id', \app\modules\Admin\models\dianpuModel::query()->where('company_name', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                }
                //按店铺掌柜查找
                if($post_data['keywordsType'] == $keywordsTypeArray['dianpu_manager_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['dianpu_manager_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['dianpu_manager_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['dianpu_manager_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部',
                'waiting'  => '待处理',
                'agreed' => '已同意',
                'denied'  => '已拒绝',
                'paid'  => '已打款',
                'finished'  => '已收款',
                'canceled' => '已取消',
            ], JSON_UNESCAPED_UNICODE));
        }
        return parent::indexAction($returnData); // TODO: Change the autogenerated stub
    }

    #[店铺提现详情]
    public function viewAction($returnData = FALSE)
    {
        $id = $this->get('id', 0);
        try {
            $apply = withdrawModel::with(['dianpu','dianpumanager', 'member', 'dianpuwithdrawlogs'])->findOrFail($id);
            $this->_view->assign('dataset', $apply->toJson());
            $this->_view->display( strtolower($this->controller) . '/view.html');
        }catch (Exception $e){
            ret(3001, $e->getMessage());
        } finally {
            unset($id);
        }
    }

    #[转帐凭证查看]
    public function showpicAction()
    {
        $id = $this->get('id', 0);
        try {
            $apply = withdrawModel::findOrFail($id);

            if(!empty($apply->paidoff_evidence_image)){
                $this->_view->assign('imgs', json_encode($apply->paidoff_evidence_image,256));
                $this->_view->display( strtolower($this->controller) . '/showpic.html');
            }else{
                throw new Exception('打款凭证未上传');
            }
        }catch (Exception $e){
            throw new Exception('申请不存在');
        }
    }

    #[同意店铺提现]
    public function doagreeAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            $is_re = $this->get('re', '0');
            try {
                $applyModel = $this->model->findOrFail($opt_id);
                if($is_re){
                    if($applyModel->status !== 2){
                        ret(5, '当前申请非已打款状态，不能设置为同意！');
                    }
                }else{
                    if($applyModel->status !== 0){
                        ret(5, '提现已经处理过，不能重复处理！');
                    }
                }
                $user = memberModel::find($applyModel->member_id);
                if(!$user){
                    ret(4, '操作失败，提现的用户不存在！');
                }
                $dianpu = \app\modules\Admin\models\dianpuModel::find($applyModel->dianpu_id);
                if(!$dianpu){
                    ret(4, '操作失败，提现的店铺不存在！');
                }
                $dianpumanager = memberModel::find($applyModel->dianpu_manager_id);
                if(!$dianpumanager){
                    ret(4, '操作失败，提现的店铺掌柜不存在！');
                }
                $res = DB::transaction(function () use ($applyModel, $is_re) {
                    $applyModel->status = 1;
                    $applyModel->updated_at = timestamp();
                    if($applyModel->save()){
                        if($is_re){
                            $remark = "打款审核未通过，管理员重新设置[用户{$applyModel->member_id}的店铺提现{$applyModel->money}元]的申请状态为【同意】";
                        }else{
                            $remark = "管理员设置[用户{$applyModel->member_id}的店铺提现{$applyModel->money}元]的申请状态为【同意】";
                        }
                        $withdraw_log_data = [
                            'event'=>'agree',
                            'event_id'=>$applyModel->id,
                            'remark'=>$remark,
                            'oper_type'=>'admin',
                            'oper_id'=>$this->auth->user_id,
                            'created_at'=>timestamp(),
                        ];
                        return withdrawLogModel::query()->insert($withdraw_log_data);
                    }else{
                        return false;
                    }
                });
                if($res){
                    ret(0, '恭喜，同意店铺提现成功！');
                }else{
                    ret(1, '抱歉，店铺提现操作失败！');
                }
            }catch (Exception $exception){
                ret(2, '操作失败，提现记录不存在或已处理！');
            } finally {
                unset($applyModel, $opt_id, $is_re, $withdraw_log_data, $remark, $res, $dianpu, $dianpumanager);
            }
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[拒绝店铺提现]
    public function dorefuseAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            $remark = $this->postData['remark']?:'';
            $is_re = $this->get('re', '0');
            try {
                $apply = $this->model->findOrFail($opt_id);
                if($is_re){
                    if($apply->status !== 1){
                        ret(7, '当前申请非已同意状态，不能设置为拒绝！');
                    }
                }else{
                    if($apply->status !== 0){
                        ret(5, '提现已经处理过，不能重复处理！');
                    }
                }
                $user = memberModel::find($apply->member_id);
                if(!$user){
                    ret(4, '操作失败，提现的用户不存在！');
                }
                $dianpu = \app\modules\Admin\models\dianpuModel::find($apply->dianpu_id);
                if(!$dianpu){
                    ret(4, '操作失败，提现的店铺不存在！');
                }
                $dianpumanager = memberModel::find($apply->dianpu_manager_id);
                if(!$dianpumanager){
                    ret(4, '操作失败，提现的店铺掌柜不存在！');
                }
                if($is_re && empty($remark)){
                    $remark = "管理员重新设置[用户{$apply->member_id}的店铺提现{$apply->money}元]的申请状态为【拒绝】";
                }else{
                    $remark = "管理员设置[用户{$apply->member_id}的店铺提现{$apply->money}元]的申请状态为【拒绝】";
                }
                $res = DB::transaction(function () use ($apply, $remark, $user) {
                    $apply->status = -1;
                    $apply->updated_at = timestamp();
                    if($apply->save()){
                        dianpuModel::moneyWithdrawFreeze($apply->money, $apply->dianpu_id, 'dianpuwithdrawdenied');
                        $withdraw_log_data = [
                            'event'=>'denied',
                            'event_id'=>$apply->id,
                            'remark'=>$remark,
                            'oper_type'=>'admin',
                            'oper_id'=>$this->auth->user_id,
                            'created_at'=>timestamp(),
                        ];
                        dianpuwithdrawlogModel::query()->insert($withdraw_log_data);
                        memberModel::money($apply->money, $apply->member_id, 'dianpuwithdrawdenied', $apply->id, "管理员{$this->auth->user_id}拒绝用户{$apply->member_id}的店铺提现申请，退回{$apply->money}元");
                        return true;
                    }else{
                        return false;
                    }
                });
                if($res){
                    ret(0, '恭喜，拒绝店铺提现操作成功！');
                }else{
                    ret(1, '抱歉，店铺提现操作失败！');
                }
            }catch (Exception $e){
                ret(2, '操作失败，提现记录不存在或已处理！');
            } finally {
                unset($opt_id, $remark, $apply, $user, $res, $is_re, $withdraw_log_data, $dianpu, $dianpumanager);
            }
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[确定店铺提现已经完成]
    public function dopaidAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            try {
                $apply = $this->model->findOrFail($opt_id);
                if($apply->status !== 2){
                    ret(5, '提现非已打款状态，无法做“确认已打款”操作！');
                }
                $user = memberModel::find($apply->member_id);
                if(!$user){
                    ret(4, '操作失败，提现的用户不存在！');
                }
                $dianpu = \app\modules\Admin\models\dianpuModel::find($apply->dianpu_id);
                if(!$dianpu){
                    ret(4, '操作失败，提现的店铺不存在！');
                }
                $dianpumanager = memberModel::find($apply->dianpu_manager_id);
                if(!$dianpumanager){
                    ret(4, '操作失败，提现的店铺掌柜不存在！');
                }
                $res = DB::transaction(function () use ($apply) {
                    $apply->status = 3;
                    $apply->updated_at = timestamp();
                    if($apply->save()){
                        dianpuModel::moneyWithdrawFreeze($apply->money, $apply->dianpu_id, 'dianpuwithdrawfinished');
                        $withdraw_log_data = [
                            'event'=>'denied',
                            'event_id'=>$apply->id,
                            'remark'=>"管理员设置[用户{$apply->member_id}的店铺提现{$apply->money}元]的申请状态为【确认已打款】",
                            'oper_type'=>'admin',
                            'oper_id'=>$this->auth->user_id,
                            'created_at'=>timestamp(),
                        ];
                        dianpuwithdrawlogModel::query()->insert($withdraw_log_data);
                        memberModel::money($apply->actual_money, $apply->dianpu_manager_id, 'dianpuwithdrawfinished', $apply->id, "管理员{$this->auth->user_id}审核通过店铺提现掌柜的打款凭证，余额增加{$apply->actual_money}元");
                        return true;
                    }else{
                        return false;
                    }
                });
                if($res){
                    ret(0, '恭喜，审核店铺提现打款凭证，操作成功！');
                }else{
                    ret(1, '抱歉，审核店铺提现打款凭证，操作失败！');
                }
            }catch (Exception $e){
                ret(2, '操作失败，提现记录不存在或已处理！');
            } finally {
                unset($opt_id, $apply, $user, $res, $withdraw_log_data, $dianpu, $dianpumanager);
            }
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }
}
